package com.ryx.service.Impl;

import com.ryx.entity.SysRolePermission;
import com.ryx.exception.GlobalException;
import com.ryx.exception.code.BaseResponseCode;
import com.ryx.mapper.SysRolePermissionMapper;
import com.ryx.service.RolePermissionService;
import com.ryx.vo.req.RolePermissionOperationReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @BelongsPackage: com.ryx.service.Impl
 * @Author: 容永轩
 * @CreateTime: 2020-12-28
 * @Description:
 */
@Service
@Transactional
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public void addRolePermission(RolePermissionOperationReqVo vo) {

        //删除关联数据再添加
        sysRolePermissionMapper.removeByRoleId(vo.getRoleId());

        if (vo.getPermissionIds() == null || vo.getPermissionIds().isEmpty()){
            return;
        }

        List<SysRolePermission> list = new ArrayList<>();


        for (String permissionId : vo.getPermissionIds()) {

            SysRolePermission sysRolePermission = new SysRolePermission();

            sysRolePermission.setId(UUID.randomUUID().toString());
            sysRolePermission.setCreateTime(new Date());
            sysRolePermission.setRoleId(vo.getRoleId());
            sysRolePermission.setPermissionId(permissionId);
            list.add(sysRolePermission);
        }
        int i = sysRolePermissionMapper.batchInsertRolePermission(list);

        if (i == 0){
            throw  new GlobalException(BaseResponseCode.OPERATION_ERROR);
        }

    }

    @Override
    public List<String> getRoleIdsByPermissionId(String permissionId) {
        return sysRolePermissionMapper.getRoleIdsByPermissionId(permissionId);
    }

    @Override
    public int removeRoleByPermissionId(String permissionId) {
        return sysRolePermissionMapper.removeByPermissionId(permissionId);
    }

    @Override
    public List<String> getPermissionIdsByRoleId(String roleId) {
        return sysRolePermissionMapper.getPermissionIdsByRoleId(roleId);
    }

    @Override
    public int removeByRoleId(String roleId) {
        return sysRolePermissionMapper.removeByRoleId(roleId);
    }

    @Override
    public List<String> getPermissionIdsByRoleIds(List<String> roleIds) {
        return sysRolePermissionMapper.getPermissionIdsByRoleIds(roleIds);
    }


}
